package com.zq.gateway.config;


import com.zq.common.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局过滤器，为请求添加 Same-Token 
 */
@Component
@Order(100)
@Slf4j
public class ForwardAuthFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        在请求头中添加凭证
        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                .header("sa-gateway","zhangqiao")
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
//后台管理端，用户登录成功，刷新token
        List<String> list = exchange.getRequest().getHeaders().get("token");
        if (list != null && list.size() > 0) {
            String token = list.get(0);
//            刷新token
            String refreshToken = jwtUtil.refreshToken(token);
            log.info("刷新后的token为：" + refreshToken);
        }

        //前台用户端，用户登录成功，刷新token
        List<String> userList = exchange.getRequest().getHeaders().get("userToken");
        if (userList != null && userList.size() > 0) {
            String token = userList.get(0);
//            刷新token
            String refreshToken = jwtUtil.refreshToken(token);
            log.info("刷新后的userToken为：" + refreshToken);
        }
        // 继续过滤链
        return chain.filter(newExchange);

    }
}
